package org.com.blbl.Client;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ClientReducer extends Reducer<Text,IntWritable,Text,Text>{
    private Map<String, Integer> countMap = new HashMap<>();
    private int totalCount = 0;

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int count = 0;
        for (IntWritable val : values) {
            count += val.get();
        }
        countMap.put(key.toString(), count);
        totalCount += count;
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        // 计算占比并输出结果
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            String deviceType = entry.getKey();
            int count = entry.getValue();
            double percentage = (double) count / totalCount * 100;
            context.write(new Text(deviceType), new Text("Count: " + count + ", Percentage: " + String.format("%.2f", percentage) + "%"));
        }
    }
}
